// pages/appointmentManagement/appointmentManagement.js

// 模拟数据生成函数
function getMockAppointments() {
    const today = new Date();
    const todayDateString = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;
    
    return [
      {
        id: 1,
        patientName: '张三',
        phone: '138****1234',
        age: 25,
        department: '口腔内科',
        doctorName: '张医生',
        date: todayDateString,
        time: '09:30',
        service: '洗牙',
        status: '待确认',
        statusClass: 'pending',
        notes: '牙齿敏感'
      },
      {
        id: 2,
        patientName: '李四',
        phone: '139****5678',
        age: 32,
        department: '正畸科',
        doctorName: '李医生',
        date: todayDateString,
        time: '10:15',
        service: '牙齿矫正咨询',
        status: '已确认',
        statusClass: 'confirmed',
        notes: ''
      },
      {
        id: 3,
        patientName: '王五',
        phone: '137****9012',
        age: 45,
        department: '修复科',
        doctorName: '王医生',
        date: todayDateString,
        time: '14:00',
        service: '种植牙复查',
        status: '已完成',
        statusClass: 'completed',
        notes: ''
      },
      {
        id: 4,
        patientName: '赵六',
        phone: '136****3456',
        age: 18,
        department: '儿童口腔科',
        doctorName: '赵医生',
        date: todayDateString,
        time: '09:00',
        service: '窝沟封闭',
        status: '已取消',
        statusClass: 'cancelled',
        notes: '临时有事'
      }
    ];
  }
  
  Page({
    data: {
      dateList: [],
      currentDateIndex: 0,
      currentStatus: 'all',
      showFilterModal: false,
      filterTime: '',
      departments: ['全部科室', '口腔内科', '口腔外科', '正畸科', '修复科', '儿童口腔科'],
      selectedDepartmentIndex: 0,
      doctors: ['全部医生', '张医生', '李医生', '王医生', '赵医生'],
      selectedDoctorIndex: 0,
      showDetailModal: false,
      currentAppointment: {},
      appointments: [],
      filteredAppointments: [],
      selectedFilters: []  // 新增：存储已选筛选条件
    },
    
    onLoad: function() {
      this.generateDateList();
      this.initAppointments();
    },
    
    initAppointments: function() {
      const mockData = getMockAppointments();
      this.setData({
        appointments: mockData
      }, () => {
        this.filterAppointments();
      });
    },
    
    generateDateList: function() {
      const dateList = [];
      const today = new Date();
      
      for (let i = 0; i < 7; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);
        
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        
        const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
        const week = weekDays[date.getDay()];
        
        dateList.push({
          date: `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`,
          day: day,
          week: `周${week}`
        });
      }
      
      this.setData({
        dateList: dateList
      });
    },
    
    filterAppointments: function() {
      const { appointments, currentStatus, currentDateIndex, dateList, 
              filterTime, selectedDepartmentIndex, departments, 
              selectedDoctorIndex, doctors } = this.data;
  
      if (!appointments || appointments.length === 0 || !dateList || dateList.length === 0) {
        this.setData({
          filteredAppointments: []
        });
        return;
      }
  
      let filtered = [...appointments];
      
      // 按日期筛选
      const selectedDate = dateList[currentDateIndex].date;
      filtered = filtered.filter(app => app.date === selectedDate);
      
      // 按状态筛选
      if (currentStatus !== 'all') {
        const statusMap = {
          'pending': '待确认',
          'confirmed': '已确认',
          'completed': '已完成',
          'cancelled': '已取消'
        };
        filtered = filtered.filter(app => app.status === statusMap[currentStatus]);
      }
      
      // 按时间段筛选
      if (filterTime) {
        const timeMap = {
          'morning': ['08', '09', '10', '11'],
          'afternoon': ['12', '13', '14', '15', '16'],
          'evening': ['17', '18', '19', '20']
        };
        filtered = filtered.filter(app => {
          const hour = app.time.split(':')[0];
          return timeMap[filterTime].includes(hour);
        });
      }
      
      // 按科室筛选
      if (selectedDepartmentIndex > 0) {
        const selectedDepartment = departments[selectedDepartmentIndex];
        filtered = filtered.filter(app => app.department === selectedDepartment);
      }
      
      // 按医生筛选
      if (selectedDoctorIndex > 0) {
        const selectedDoctor = doctors[selectedDoctorIndex];
        filtered = filtered.filter(app => app.doctorName === selectedDoctor);
      }
      
      this.setData({
        filteredAppointments: filtered
      });
    },
    
    // 新增：更新已选筛选条件标签
    updateSelectedFilters: function() {
      const { filterTime, selectedDepartmentIndex, departments, selectedDoctorIndex, doctors } = this.data;
      const selectedFilters = [];
      
      // 时间段筛选标签
      if (filterTime) {
        const timeLabels = {
          'morning': '上午',
          'afternoon': '下午',
          'evening': '晚上'
        };
        selectedFilters.push({
          type: 'time',
          text: `时间段: ${timeLabels[filterTime]}`
        });
      }
      
      // 科室筛选标签
      if (selectedDepartmentIndex > 0) {
        selectedFilters.push({
          type: 'department',
          text: `科室: ${departments[selectedDepartmentIndex]}`
        });
      }
      
      // 医生筛选标签
      if (selectedDoctorIndex > 0) {
        selectedFilters.push({
          type: 'doctor',
          text: `医生: ${doctors[selectedDoctorIndex]}`
        });
      }
      
      this.setData({
        selectedFilters: selectedFilters
      });
    },
    
    // 新增：移除单个筛选条件
    removeFilter: function(e) {
      const index = e.currentTarget.dataset.index;
      const { selectedFilters } = this.data;
      const filterToRemove = selectedFilters[index];
      
      // 根据筛选类型重置对应筛选条件
      switch (filterToRemove.type) {
        case 'time':
          this.setData({ filterTime: '' });
          break;
        case 'department':
          this.setData({ selectedDepartmentIndex: 0 });
          break;
        case 'doctor':
          this.setData({ selectedDoctorIndex: 0 });
          break;
      }
      
      // 更新筛选标签并重新筛选
      this.updateSelectedFilters();
      this.filterAppointments();
    },
    
    // 新增：清空所有筛选条件
    clearAllFilters: function() {
      this.setData({
        filterTime: '',
        selectedDepartmentIndex: 0,
        selectedDoctorIndex: 0
      }, () => {
        this.updateSelectedFilters();
        this.filterAppointments();
      });
    },
    
    selectDate: function(e) {
      const index = e.currentTarget.dataset.index;
      this.setData({
        currentDateIndex: index
      }, () => {
        this.filterAppointments();
      });
    },
    
    filterByStatus: function(e) {
      const status = e.currentTarget.dataset.status;
      this.setData({
        currentStatus: status
      }, () => {
        this.filterAppointments();
      });
    },
    
    showFilter: function() {
      this.setData({ showFilterModal: true });
    },
    
    hideFilter: function() {
      this.setData({ showFilterModal: false });
    },
    
    selectTime: function(e) {
      const time = e.currentTarget.dataset.time;
      this.setData({
        filterTime: this.data.filterTime === time ? '' : time
      });
    },
    
    selectDepartment: function(e) {
      this.setData({
        selectedDepartmentIndex: e.detail.value
      });
    },
    
    selectDoctor: function(e) {
      this.setData({
        selectedDoctorIndex: e.detail.value
      });
    },
    
    resetFilter: function() {
      this.setData({
        filterTime: '',
        selectedDepartmentIndex: 0,
        selectedDoctorIndex: 0
      });
    },
    
    confirmFilter: function() {
      this.hideFilter();
      this.updateSelectedFilters();  // 新增：更新筛选标签
      this.filterAppointments();
    },
    
    showDetail: function(e) {
      const id = e.currentTarget.dataset.id;
      const appointment = this.data.appointments.find(app => app.id === id);
      
      this.setData({
        currentAppointment: appointment || {},
        showDetailModal: true
      });
    },
    
    hideDetail: function() {
      this.setData({ showDetailModal: false });
    },
    
    cancelAppointment: function() {
      const { currentAppointment, appointments } = this.data;
      
      if (!currentAppointment || !currentAppointment.id) return;
      
      wx.showModal({
        title: '提示',
        content: '确定要取消该预约吗？',
        success: (res) => {
          if (res.confirm) {
            const updatedAppointments = appointments.map(app => {
              if (app.id === currentAppointment.id) {
                return {
                  ...app,
                  status: '已取消',
                  statusClass: 'cancelled'
                };
              }
              return app;
            });
            
            this.setData({
              appointments: updatedAppointments,
              currentAppointment: {
                ...currentAppointment,
                status: '已取消',
                statusClass: 'cancelled'
              }
            }, () => {
              this.filterAppointments();
            });
          }
        }
      });
    },
    
    confirmAppointment: function() {
      const { currentAppointment, appointments } = this.data;
      
      if (!currentAppointment || !currentAppointment.id) return;
      
      wx.showModal({
        title: '提示',
        content: '确定要确认该预约吗？',
        success: (res) => {
          if (res.confirm) {
            const updatedAppointments = appointments.map(app => {
              if (app.id === currentAppointment.id) {
                return {
                  ...app,
                  status: '已确认',
                  statusClass: 'confirmed'
                };
              }
              return app;
            });
            
            this.setData({
              appointments: updatedAppointments,
              currentAppointment: {
                ...currentAppointment,
                status: '已确认',
                statusClass: 'confirmed'
              }
            }, () => {
              this.filterAppointments();
            });
          }
        }
      });
    },
    
    completeAppointment: function() {
      const { currentAppointment, appointments } = this.data;
      
      if (!currentAppointment || !currentAppointment.id) return;
      
      wx.showModal({
        title: '提示',
        content: '确定该预约已完成吗？',
        success: (res) => {
          if (res.confirm) {
            const updatedAppointments = appointments.map(app => {
              if (app.id === currentAppointment.id) {
                return {
                  ...app,
                  status: '已完成',
                  statusClass: 'completed'
                };
              }
              return app;
            });
            
            this.setData({
              appointments: updatedAppointments,
              currentAppointment: {
                ...currentAppointment,
                status: '已完成',
                statusClass: 'completed'
              }
            }, () => {
              this.filterAppointments();
            });
          }
        }
      });
    }
  });